package webapp;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import mda.annotation.CopyFile;
import flca.mda.api.util.DbUnitUtils;
import flca.mda.api.util.TypeUtils;
import flca.mda.codegen.data.ITemplate;
import flca.mda.codegen.data.ITemplateHooks;
import flca.mda.codegen.helpers.IPostProcess;

public class WebappJavaTemplateHooks implements ITemplateHooks {
	
	private static final WebappCodeMerger sCodeMerger = new WebappCodeMerger();

	private static List<IPostProcess> sPostprocessors = null;

	private static final TypeUtils tu = new TypeUtils();
	
	static {
		sPostprocessors = new ArrayList<>();
		sPostprocessors.add(new ReplaceImportsPostprocessor());
		sPostprocessors.add(new RemoveNotUsedImportsPostprocessor());
	}

	@Override
	public void doBeforeGenerate(Class<?> aCurrentClass, ITemplate aTemple) {
	}

	@Override
	public String doAfterGenerate(String aGeneratedSource, Class<?> aCurrentClass, ITemplate aTemplate) {
		
		String result = aGeneratedSource;
		
		for (IPostProcess postproc : sPostprocessors) {
			if (result != null && !result.isEmpty()) {
				result = postproc.parse(result, aTemplate, aCurrentClass);
			}
		}
		return result;
	}

	@Override
	public void doSetupOnce() {
	}

	@Override
	public void doTeardownOnce() {
		DbUnitUtils.reset();
	}

	@Override
	public String doMerge(String aNewCode, File aOldFile, Class<?> aCurrentClass, ITemplate aTemplate) {
		return sCodeMerger.doMerge(aNewCode, aOldFile, aCurrentClass, aTemplate);
	}

	@Override
	public String doGenerateFilename(String aGeneratedFilename, ITemplate aTemplate, Class<?> aCurrentClass) {
		return null;
	}

	@Override
	public boolean copyModelClass(Class<?> aModelclass) {
		if (aModelclass != null) {
			if (tu.hasType(aModelclass, CopyFile.class)) {
				return true;
			}

			if (aModelclass.isEnum()) {
				return true;
			}
			if (tu.hasType(aModelclass, Exception.class)) {
				return true;
			}
		}

		return false;
	}
	
	
}
